package com.unicom.proxy.cglibproxy;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @author liry
 * @version 1.0
 * @date Created on 2022/1/3 20:54
 * Description:
 */
public class CglibDynamicProxy implements MethodInterceptor {

    public static final Logger log = LoggerFactory.getLogger(CglibDynamicProxy.class);

    // 定义被代理对象
    private Object target;

    public CglibDynamicProxy(Object target) {
        this.target = target;
    }

    // 创建代理对象
    public Object getProxy() {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(target.getClass());
        enhancer.setClassLoader(target.getClass().getClassLoader());
        // 设置MethodInterceptor回调
        enhancer.setCallback(this);

        return enhancer.create();
    }

    // 方法回调
    @Override
    public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
        log.info("------cglib动态代理: 执行目标方法开始-------");
        Object returnVal = method.invoke(target, args);
        log.info("------cglib动态代理: 执行目标方法结束-------");
        return returnVal;
    }
}
